<template>
  <div class="all">
    <div class="top">
      <el-row>
        <el-form ref="form" inline label-position="left">
          <el-col :span="3">
            <el-form-item label="编号">
              <el-input v-model="query.coding" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :label="$t('app.stock.parts.name')">
              <el-input v-model="query.name" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="规格型号">
              <el-input v-model="query.spec" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :label="$t('app.stock.parts.brand')">
              <el-input v-model="query.brand" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="备件类别">
              <v-select v-model="query.category_id" action="partsCategoryList" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :label="$t('app.stock.parts.admin')">
              <SelectS v-model="query.admin_id" action="adminList" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :label="$t('app.status')">
              <SelfSelect v-model="query.status" :show-list="status" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :label="$t('app.stock.parts.department')">
              <SelectS v-model="query.department_id" action="departmentList" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-button style="margin-top: 38%" icon="el-icon-search" type="primary" @click="index">查找</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row class="btns">
        <el-button v-if="roles.includes('StockPartsAdd')" type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd">{{ $t('button.create') }}</el-button>
        <el-button type="primary" icon="el-icon-printer" @click="exportDialog">{{ $t('button.export') }}</el-button>
        <div class="buttonBox">
          <el-upload v-if="roles.includes('StockPartsImport')" :show-file-list="false" action="" :before-upload="file => workbook(file)">
            <el-button type="primary" icon="el-icon-edit" size="mini">{{ $t('button.import') }}</el-button>
          </el-upload>
        </div>
        <el-button v-if="roles.includes('StockPartsDelete')" type="danger" icon="el-icon-delete" @click="delBtn">{{ $t('button.delete') }}</el-button>
        <el-button v-if="roles.includes('StockPartsImport')" type="primary" icon="el-icon-download" @click="downloadExcel">{{ $t('button.template') }}</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh">{{ $t('button.refresh') }}</el-button>
      </el-row>
      <span class="total">{{ $t('app.count') }}：{{ total }}</span>
    </div>
    <div class="main">
      <div class="table">
        <el-table ref="multipleTable" v-loading="loading" border tooltip-effect="dark" width="100%" height="60vh" stripe :data="data.dataList" @selection-change="handleSelectionChange">
          <el-table-column :label="$t('app.Num')" type="index" align="center" width="50" />
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column prop="coding" label="编号" align="center" width="180" show-overflow-tooltip />
          <el-table-column prop="department" label="部门" align="center" width="150" show-overflow-tooltip />
          <el-table-column prop="name" label="备件名称" align="center" width="180" show-overflow-tooltip />
          <el-table-column prop="spec" label="规格型号" align="center" width="320" show-overflow-tooltip />
          <el-table-column prop="brand" label="品牌" align="center" show-overflow-tooltip />
          <el-table-column prop="unit" label="单位" align="center" show-overflow-tooltip />
          <el-table-column prop="price" label="单价" align="center" show-overflow-tooltip />
          <el-table-column prop="last_month_number" label="期初" align="center" show-overflow-tooltip />
          <el-table-column prop="month_enter" label="本月入库" align="center" show-overflow-tooltip />
          <el-table-column prop="month_out" label="本月出库" align="center" show-overflow-tooltip />
          <el-table-column prop="number" label="本月结存" align="center" show-overflow-tooltip />
          <el-table-column prop="store_location" label="备注" align="center" width="150" show-overflow-tooltip />
          <el-table-column prop="min_number" label="低储" align="center" show-overflow-tooltip />
          <el-table-column prop="max_number" label="高储" align="center" show-overflow-tooltip />
          <el-table-column prop="store" label="仓库" align="center" show-overflow-tooltip />
          <el-table-column prop="category" label="备件类别" align="center" width="150" show-overflow-tooltip />
          <el-table-column prop="provider" label="供应商" align="center" show-overflow-tooltip />
          <el-table-column prop="admin" label="负责人" align="center" show-overflow-tooltip />
          <el-table-column prop="cost" label="成本中心" align="center" width="120" show-overflow-tooltip />
          <el-table-column :label="$t('app.status')" align="center">
            <template scope="{row}">
              <div v-html="row.status_table" />
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" align="center" width="100" />
          <el-table-column prop="year_out" label="今年出库" align="center" width="100" />
          <el-table-column prop="used_equipment" label="适用于资产" align="center" width="300" show-overflow-tooltip />
          <el-table-column prop="used_jig" label="适用于工装" align="center" width="300" show-overflow-tooltip />
          <el-table-column prop="used_facility" label="适用于设施" align="center" width="300" show-overflow-tooltip />
          <el-table-column prop="used" label="适用于" align="center" />
          <el-table-column v-if="roles.includes('StockPartsDetail' || 'StockPartsDelete')" :label="$t('app.handle')" fixed="right" width="180" align="center">
            <template scope="{row}">
              <el-button v-if="roles.includes('StockPartsDetail')" type="primary" @click="goDetail(row.id)">{{ $t('button.edit') }}</el-button>
              <el-button v-if="roles.includes('StockPartsDelete')" type="danger" @click="handleDel(row.id)">{{ $t('button.delete') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="page" align="center" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
      </div>
      <el-dialog v-loading="isLoading" title="请选择导出字段" :visible.sync="excelDialog" width="60%" :element-loading-text="loadingExcel" element-loading-spinner="el-icon-loading">
        <div>
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group v-model="needExport" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="title in tableHead" :key="title" class="checkStyle" :label="title" />
          </el-checkbox-group>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="excelDialog = false">取 消</el-button>
          <el-button type="primary" @click="exportExcel">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import API from '@/api/stock/parts'
import VSelect from '@/components/select'
import SelectS from '@/components/select-search.vue'
import { status, department } from '@/utils/option'
import SelfSelect from '@/components/select-o'
import { partsTables } from '@/utils/Table'
import XLSX from 'xlsx'
import { mapGetters } from 'vuex'
const tableOptions = ['部门', '备件类别', '编号', '成本中心', '适用于', '负责人', '备件名称', '规格型号', '品牌', '供应商', '单位', '单价', '期初', '低储', '高储', '本月入库', '本月出库', '本月结存', '状态', '仓库', '备注', '排序', '适用于资产', '适用于工装', '适用于设施', '适用于资产分类']
export default {
  components: {
    SelfSelect,
    VSelect,
    SelectS
  },
  inject: ['goUrl', 'paramCategory', 'reload'],
  data() {
    return {
      data: {
        dataList: []
      },
      total: 0,
      adminList: [],
      loading: true,
      positionTree: [],
      categoryTree: [],
      query: {
        limit: 15,
        page: 1
      },
      status,
      department,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      categoryProps: {
        children: 'children',
        label: 'name'
      },
      isLoading: false,
      loadingExcel: '正在导出...',
      multipleSelection: [],
      needExport: ['部门', '备件类别', '编号', '成本中心', '负责人', '备件名称', '规格型号', '品牌', '供应商', '单位', '单价', '期初', '低储', '高储', '本月入库', '本月出库', '本月结存', '状态', '仓库', '备注', '排序', '适用于资产', '适用于工装', '适用于设施', '适用于资产分类', '适用于'],
      excelDialog: false,
      exportList: [],
      exportList1: [],
      exportList2: [],
      exportList3: [],
      exportList4: [],
      partsTables,
      isIndeterminate: true,
      tableHead: tableOptions,
      checkAll: true
    }
  },
  computed: {
    ...mapGetters(['roles']),
    pages() {
      return this.total / 1000 + 1
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
    window.addEventListener('keydown', this.handKeyCode, true)
    // this.abc(1).then(res => {
    //   // console.log(this.testList)
    // })
  },
  methods: {
    index() {
      this.loading = true
      API.getList(this.query).then(res => {
        this.data.dataList = res.data.data
        this.total = res.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    setStorage() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
    },
    handKeyCode(e) {
      if (e.keyCode === 13 || e.keyCode === 32) { // 回车搜索
        this.index()
      }
    },
    goDetail(id) {
      const url = `/parts/edit/${id}`
      this.setStorage()
      this.goUrl(url)
    },
    handleAdd() {
      this.setStorage()
      this.goUrl('/parts/add')
    },
    categoryFormatter(row) {
      return this.paramCategory(row)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.delete(id).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.$message.success('删除成功')
            this.setStorage()
            this.index()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    delBtn() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const idArray = []
        this.multipleSelection.forEach(item => {
          idArray.push(item.id)
        })
        const id = idArray.join(',')
        this.handleDel(id)
      } else {
        this.$message('请先选择，然后再删除')
      }
    },
    refresh() {
      this.reload()
    },
    exportDialog() {
      this.excelDialog = true
    },
    handleCheckAllChange(val) {
      this.needExport = val ? tableOptions : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.tableHead.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableHead.length
    },
    downloadExcel() {
      const a = document.createElement('a')
      a.href = 'https://d.ubeiyun.com/xls/%E5%A4%87%E4%BB%B6%E5%8F%B0%E8%B4%A6.xlsx'
      a.download = '备件模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    workbook(file) {
      this.loading = true
      const reader = new FileReader()
      const self = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        const postData = {}
        postData.outData = outData
        API.excel(postData).then(response => {
          if (response.data.error_code === 1) {
            self.$message.success(`恭喜你，操作成功`)
            self.loading = false
            self.index()
          } else {
            self.$message.error(response.data.message)
            self.loading = false
            self.index()
          }
        }).finally(() => {
          self.loading = false
          self.index()
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    toExcel() {
      const exportData = []
      const exportTitle = []
      const titleObj = this.partsTables
      exportData.push(this.needExport)
      for (const keys of this.needExport) {
        exportTitle.push(Object.keys(titleObj).find(key => titleObj[key] === keys))
      }
      this.exportList.forEach(item => {
        const arr = []
        for (const key of exportTitle) {
          arr.push(item[key])
        }
        exportData.push(arr)
      })
      const ws = XLSX.utils.aoa_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      /* save to file */
      this.refresh()
      this.loading = false
      this.excelDialog = false
      XLSX.writeFile(wb, '备件台账.xlsx')
    },
    async getExcel(condition) {
      this.exportList = []
      const res = await API.getList(condition)
      const exportList = res.data.data
      const total = res.data.total
      this.exportList.push(...exportList)
      if (this.exportList.length === total) {
        this.isLoading = false
        this.toExcel()
      }
    },
    allExcel() {
      this.isLoading = true
      const arr = Object.keys(this.query)
      const len = arr.length
      if (len > 4 || this.query.admin_id || this.query.category_id) {
        const condition = this.query
        condition.limit = this.total
        condition.page = 1
        this.getExcel(condition)
      } else {
        for (let i = 1; i <= this.pages; i++) {
          const condition = {
            limit: 1000,
            page: i
          }
          this.getExcel(condition)
        }
      }
    },
    exportExcel() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.exportList = this.multipleSelection
        this.toExcel()
      } else {
        this.allExcel()
      }
    }
  }
}
</script>

<style scoped>

</style>
